package com.eurake.seckill.controller;

import com.eurake.seckill.pojo.User;
import com.eurake.seckill.service.IGoodsService;
import com.eurake.seckill.service.IUserService;
import com.eurake.seckill.vo.DetailVo;
import com.eurake.seckill.vo.GoodsVo;
import com.eurake.seckill.vo.RespBean;
import com.eurake.seckill.vo.RespBeanEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;


import java.io.StringWriter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    IUserService userService;
    @Resource
    IGoodsService goodsService;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    ThymeleafViewResolver thymeleafViewResolver;

    //优化前：QPS：2200
    //页面静态化：QPS：9000
    @RequestMapping(value="/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model,User user) {
        if(user == null){
            return "login";
        }
        //从redis中获取缓存页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String)valueOperations.get("goodsList");
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        //还没加入redis，手动渲染并加入redis
        //手动渲染页面
        Context context = new Context();
        context.setVariable("user",user);
        context.setVariable("goodsList",goodsService.findGoodsVo());
        StringWriter writer = new StringWriter();
        thymeleafViewResolver.getTemplateEngine().process("goodsList",context,writer);
        html = writer.toString();
        if(!StringUtils.isEmpty(html)){
             valueOperations.set("goodsList",html,1, TimeUnit.MINUTES);
        }
        return html;
    }

    @RequestMapping(value = "/toDetail2/{goodId}",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail2(@PathVariable("goodId") long goodId,User user, Model model) {
        model.addAttribute("user", user);
        //秒杀状态
        int secKillStatus = 0;
        int remainSeconds = 0;

        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodId);
        Date startTime = goodsVo.getStartDate();
        Date endTime = goodsVo.getEndDate();
        Date now = new Date();
        if(now.before(startTime)){
            //秒杀未开始
            remainSeconds = (int)((startTime.getTime() - now.getTime())/1000);
        }else if(now.after(endTime)){
            //秒杀以结束
            secKillStatus = 2;
            remainSeconds = -1;
        }else{
            //秒杀进行时
            secKillStatus = 1;
        }
//        System.out.println(remainSeconds);
//        model.addAttribute("remainSeconds",remainSeconds);
//        model.addAttribute("secKillStatus",secKillStatus);
//        model.addAttribute("goods",goodsVo);

        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String)valueOperations.get("goodsDetails"+goodId);
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        //还没加入redis，手动渲染并加入redis
        //手动渲染页面
        Context context = new Context();
        context.setVariable("remainSeconds",remainSeconds);
        context.setVariable("secKillStatus",secKillStatus);
        context.setVariable("goods",goodsVo);
        StringWriter writer = new StringWriter();
        thymeleafViewResolver.getTemplateEngine().process("goodsDetails",context,writer);
        html = writer.toString();
        if(!StringUtils.isEmpty(html)){
            valueOperations.set("goodsDetails"+goodId,html,1, TimeUnit.MINUTES);
        }
        return html;
//        return "goodsDetails";
    }

    @RequestMapping(value = "/toDetail/{goodId}")
    @ResponseBody
    public RespBean toDetail(@PathVariable("goodId") long goodId,User user) {
        //秒杀状态
        int secKillStatus = 0;
        int remainSeconds = 0;

        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodId);
        Date startTime = goodsVo.getStartDate();
        Date endTime = goodsVo.getEndDate();
        Date now = new Date();
        if(now.before(startTime)){
            //秒杀未开始
            remainSeconds = (int)((startTime.getTime() - now.getTime())/1000);
        }else if(now.after(endTime)){
            //秒杀以结束
            secKillStatus = 2;
            remainSeconds = -1;
        }else{
            //秒杀进行时
            secKillStatus = 1;
        }
        DetailVo detailVo = new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoods(goodsVo);
        detailVo.setRemainSeconds(remainSeconds);
        detailVo.setSeckillStatus(secKillStatus);
        return RespBean.success(detailVo);
//        return "goodsDetails";
    }
}
